package com.pandora.common.util;

import org.patchca.color.ColorFactory;
import org.patchca.filter.predefined.*;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.word.RandomWordFactory;

import java.awt.*;
import java.util.Random;

/**
 * @author Daniel Wang
 * @date 2018/1/16
 */
public class CaptchaUtil {
    public  final static String IMAGE_TYPE="png";
    public  final static String REDIS_KEY="captcha_phone_";
    private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
    private static Random random = new Random();
    static {
        cs.setColorFactory(new ColorFactory() {
            @Override
            public Color getColor(int x) {
                int[] c = new int[3];
                int i = random.nextInt(c.length);
                for (int fi = 0; fi < c.length; fi++){
                    if(fi == i){
                        c[fi] = random.nextInt(71);
                    }
                    else {
                        c[fi] = random.nextInt(256);
                    }
                }
                return new Color(c[0], c[1], c[2]);
            }
        });

        RandomWordFactory wf = new RandomWordFactory();
        wf.setCharacters("123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        wf.setMaxLength(4);
        wf.setMinLength(4);
        cs.setWordFactory(wf);
    }

    public static ConfigurableCaptchaService getCaptchaService(){
        switch (random.nextInt(5)){
            case 0:
                cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
                break;
            case 1:
                cs.setFilterFactory(new MarbleRippleFilterFactory());
                break;
            case 2:
                cs.setFilterFactory(new DoubleRippleFilterFactory());
                break;
            case 3:
                cs.setFilterFactory(new WobbleRippleFilterFactory());
                break;
            case 4:
                cs.setFilterFactory(new DiffuseRippleFilterFactory());
                break;
            default:
                break;
        }
        return cs;
    }

    public static boolean equals(String source, String target){
        if(source != null && source.equalsIgnoreCase(target)){
            return true;
        }
        return false;
    }
}
